<template>
  <div class="table-page">
    <!-- 搜索表单 -->
    <a-form :model="queryForm" class="search-form" layout="inline">
      <div class="form-content">
        <a-form-item field="name" label="姓名">
          <a-input v-model="queryForm.name" placeholder="请输入姓名" allow-clear />
        </a-form-item>
        <a-form-item field="gender" label="性别">
          <a-select v-model="queryForm.gender" placeholder="请选择性别" allow-clear>
            <a-option :value="1">男</a-option>
            <a-option :value="2">女</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="dateRange" label="入职日期">
          <a-range-picker
            v-model="dateRange"
            style="width: 240px"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </div>
    </a-form>

    <!-- 工具栏 -->
    <div class="action-bar">
      <a-space>
        <a-button type="primary" @click="openAddDialog">
          <template #icon><icon-plus /></template>
          新增员工
        </a-button>
        <a-popconfirm
          content="确定要删除选中的员工吗？"
          :disabled="selectedKeys.length === 0"
          @ok="handleBatchDelete"
        >
          <a-button
            status="danger"
            :disabled="selectedKeys.length === 0"
          >
            <template #icon><icon-delete /></template>
            批量删除
          </a-button>
        </a-popconfirm>
      </a-space>
    </div>

    <!-- 数据表格 -->
    <div class="gi_table_box">
      <a-table
        row-key="id"
        :loading="loading"
        :columns="columns"
        :data="data"
        :pagination="{
          total: pagination.total,
          current: pagination.current,
          pageSize: pagination.pageSize,
          showTotal: true,
          showJumper: true,
          showPageSize: true,
          pageSizeOptions: [10, 20, 50, 100],
        }"
        :row-selection="rowSelection"
        :scroll="{ x: '100%', y: '100%' }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #name="{ record }">
          <GiCellAvatar :avatar="record.image || ''" :name="record.name"></GiCellAvatar>
        </template>
        <template #gender="{ record }">
          {{ record.gender === 1 ? '男' : '女' }}
        </template>
        <template #position="{ record }">
          {{ positionMap[record.position] }}
        </template>
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleEdit(record)">
              <template #icon><icon-edit /></template>
              编辑
            </a-button>
            <a-popconfirm
              content="确定要删除这个员工吗？"
              @ok="handleDelete(record)"
            >
              <a-button type="text" size="small" status="danger">
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </div>

    <!-- 新增/编辑对话框 -->
    <EmpDialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :emp-data="currentEmp"
      @success="handleSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import EmpDialog from './components/EmpDialog.vue'
import type { EmpQuery, Employee } from '@/apis/system/emp'
import { deleteEmps, getEmpList } from '@/apis/system/emp'
import GiCellAvatar from '@/components/GiCell/GiCellAvatar.vue'

// 职位映射
const positionMap: Record<number, string> = {
  1: '班主任',
  2: '讲师',
  3: '学工主管',
  4: '教研主管',
  5: '咨询师'
}

// 表格列定义
const columns: TableColumnData[] = [
  { title: '姓名', dataIndex: 'name', slotName: 'name', width: 120 },
  { title: '性别', slotName: 'gender' },
  { title: '职位', slotName: 'position' },
  { title: '部门', dataIndex: 'deptName' },
  { title: '入职日期', dataIndex: 'hireDate' },
  { title: '操作', slotName: 'operations', width: 180, fixed: 'right' }
]

// 查询表单
const queryForm = reactive<EmpQuery>({
  name: undefined,
  gender: undefined,
  begin: undefined,
  end: undefined,
  page: 1,
  pageSize: 10
})

// 日期范围
const dateRange = ref<[Date, Date] | undefined>()

// 表格数据和加载状态
const data = ref<Employee[]>([])
const loading = ref(false)
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10
})

// 选择行
const selectedKeys = ref<number[]>([])
const rowSelection = {
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
  onChange: (selectedRowKeys: number[]) => {
    selectedKeys.value = selectedRowKeys
  }
}

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentEmp = ref<Employee>()

// 获取员工列表
const fetchData = async () => {
  loading.value = true
  try {
    // 处理日期范围
    if (dateRange.value) {
      queryForm.begin = dayjs(dateRange.value[0]).format('YYYY-MM-DD')
      queryForm.end = dayjs(dateRange.value[1]).format('YYYY-MM-DD')
    } else {
      queryForm.begin = undefined
      queryForm.end = undefined
    }

    const res = await getEmpList(queryForm)
    if (res.code === 1) {
      data.value = res.data.rows
      pagination.total = res.data.total
      pagination.current = queryForm.page
      pagination.pageSize = queryForm.pageSize
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryForm.page = 1 // 重置到第一页
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  queryForm.name = undefined
  queryForm.gender = undefined
  queryForm.begin = undefined
  queryForm.end = undefined
  queryForm.page = 1
  queryForm.pageSize = 10
  fetchData()
}

// 分页改变
const onPageChange = (current: number) => {
  queryForm.page = current
  fetchData()
}

// 每页条数改变
const onPageSizeChange = (pageSize: number) => {
  queryForm.pageSize = pageSize
  queryForm.page = 1 // 切换每页条数时重置到第一页
  fetchData()
}

// 打开新增对话框
const openAddDialog = () => {
  dialogTitle.value = '新增员工'
  currentEmp.value = undefined
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (record: Employee) => {
  dialogTitle.value = '编辑员工'
  currentEmp.value = { ...record }
  dialogVisible.value = true
}

// 删除员工
const handleDelete = async (record: Employee) => {
  try {
    const res = await deleteEmps(record.id!.toString())
    if (res.code === 1) {
      Message.success('删除成功')
      fetchData()
    }
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    const res = await deleteEmps(selectedKeys.value.join(','))
    if (res.code === 1) {
      Message.success('删除成功')
      selectedKeys.value = []
      fetchData()
    }
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 新增/编辑成功回调
const handleSuccess = () => {
  fetchData()
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="less">
.table-page {
  height: 100%;
  overflow: hidden;
  margin: 20px;
  background: var(--color-bg-1);
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.search-form {
  margin-bottom: 20px;

  .form-content {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 16px;

    :deep(.arco-form-item) {
      margin-bottom: 0;
    }
  }
}

.action-bar {
  margin-bottom: 16px;
}

.gi_table_box {
  flex: 1;
  position: relative;
  overflow: hidden;

  :deep(.arco-table) {
    height: 100%;
  }

  :deep(.arco-table-container) {
    height: 100%;
  }

  :deep(.arco-spin) {
    height: 100%;
  }

  :deep(.arco-table-content) {
    height: 100%;
  }

  :deep(.arco-table-body) {
    height: 100%;
    overflow-y: auto;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
}
</style>
